package org.example.demo1.servlets.ManagePage;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.demo1.DAO.PermissionDao;
import org.example.demo1.DAO.RoleDao;
import org.example.demo1.DAO.RolePermissionDao;
import org.example.demo1.Entity.Permission;
import org.example.demo1.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/API/role/permission")
public class RolePermissionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        // 获取角色ID参数
        String roleIdStr = req.getParameter("role_id");
        
        // 检查参数是否存在
        if (roleIdStr == null || roleIdStr.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "缺少必要参数: role_id");
            out.print(new Gson().toJson(errorResponse));
            return;
        }
        
        int roleId;
        try {
            roleId = Integer.parseInt(roleIdStr);
        } catch (NumberFormatException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "无效的角色ID格式");
            out.print(new Gson().toJson(errorResponse));
            return;
        }
        
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            PermissionDao permissionDao = sqlSession.getMapper(PermissionDao.class);
            RolePermissionDao rolePermissionDao = sqlSession.getMapper(RolePermissionDao.class);
            
            // 获取所有权限
            List<Permission> allPermissions = permissionDao.getAllPermissions();
            
            // 获取角色拥有的权限ID列表
            List<Integer> rolePermissionIds = rolePermissionDao.getPermissionIdsByRoleId(roleId);
            
            // 构建响应数据
            List<Map<String, Object>> permissionsWithStatus = new ArrayList<>();
            
            for (Permission permission : allPermissions) {
                Map<String, Object> permissionMap = new HashMap<>();
                permissionMap.put("permission_id", permission.getPermission_id());
                permissionMap.put("permission_name", permission.getPermission_name());
                permissionMap.put("description", permission.getDescription());
                // 判断该权限是否属于该角色
                permissionMap.put("has_permission", rolePermissionIds.contains(permission.getPermission_id()));
                
                permissionsWithStatus.add(permissionMap);
            }
            
            // 构建最终响应
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", permissionsWithStatus);
            
            out.print(new Gson().toJson(response));
            
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            out.print(new Gson().toJson(errorResponse));
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
            out.flush();
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        // 读取请求体中的JSON数据
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        
        // 解析JSON数据
        Gson gson = new Gson();
        Map<String, Object> requestData;
        try {
            requestData = gson.fromJson(sb.toString(), new TypeToken<Map<String, Object>>(){}.getType());
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "无效的JSON格式");
            out.print(gson.toJson(errorResponse));
            return;
        }
        
        // 获取角色ID和权限ID列表
        Integer roleId = null;
        List<Integer> permissionIds = new ArrayList<>();
        
        try {
            if (requestData.containsKey("role_id")) {
                roleId = ((Double) requestData.get("role_id")).intValue();
            }
            
            if (requestData.containsKey("permission_ids")) {
                List<Double> doubleList = (List<Double>) requestData.get("permission_ids");
                for (Double d : doubleList) {
                    permissionIds.add(d.intValue());
                }
            }
        } catch (ClassCastException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "参数格式错误");
            out.print(gson.toJson(errorResponse));
            return;
        }
        
        // 检查必要参数
        if (roleId == null) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "缺少必要参数: role_id");
            out.print(gson.toJson(errorResponse));
            return;
        }
        
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            RolePermissionDao rolePermissionDao = sqlSession.getMapper(RolePermissionDao.class);
            
            // 先删除该角色的所有权限
            rolePermissionDao.removeAllPermissionsFromRole(roleId);
            
            // 如果有新的权限列表，则批量添加
            if (!permissionIds.isEmpty()) {
                rolePermissionDao.batchAssignPermissionsToRole(roleId, permissionIds);
            }
            
            // 提交事务
            sqlSession.commit();
            
            // 构建成功响应
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "角色权限更新成功");
            
            out.print(gson.toJson(response));
            
        } catch (Exception e) {
            // 发生异常时回滚事务
            if (sqlSession != null) {
                sqlSession.rollback();
            }
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            out.print(gson.toJson(errorResponse));
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
            out.flush();
        }
    }
    
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        // 获取角色ID参数
        String roleIdStr = req.getParameter("role_id");
        
        // 检查参数是否存在
        if (roleIdStr == null || roleIdStr.isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "缺少必要参数: role_id");
            out.print(new Gson().toJson(errorResponse));
            return;
        }
        
        int roleId;
        try {
            roleId = Integer.parseInt(roleIdStr);
        } catch (NumberFormatException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "无效的角色ID格式");
            out.print(new Gson().toJson(errorResponse));
            return;
        }
        
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            RolePermissionDao rolePermissionDao = sqlSession.getMapper(RolePermissionDao.class);
            
            // 先删除角色的所有权限关联
            rolePermissionDao.removeAllPermissionsFromRole(roleId);
            
            // 获取RoleDao并删除角色
            RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
            int result = roleDao.deleteRole(roleId);
            
            if (result > 0) {
                // 提交事务
                sqlSession.commit();
                
                // 构建成功响应
                Map<String, Object> response = new HashMap<>();
                response.put("code", 200);
                response.put("message", "角色删除成功");
                out.print(new Gson().toJson(response));
            } else {
                // 回滚事务
                sqlSession.rollback();
                
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 500);
                errorResponse.put("message", "角色删除失败");
                out.print(new Gson().toJson(errorResponse));
            }
            
        } catch (Exception e) {
            // 发生异常时回滚事务
            if (sqlSession != null) {
                sqlSession.rollback();
            }
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            out.print(new Gson().toJson(errorResponse));
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
            out.flush();
        }
    }
}
